<?php

namespace App\Http\Controllers\Admin\Member\Provider;

use App\B2BProject\Admin\AdminControllerBuildTrait;
use App\B2BProject\Area;
use App\B2BProject\AttachmentPrivateFiles;
use App\B2BProject\Custom\Business\Store;
use App\B2BProject\Custom\Member;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class ProviderController extends Controller
{
    use AdminControllerBuildTrait;

    protected $moduleName = '';

    /**
     * 供应商列表
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = Member::selectProvider()->orderBy('created_at', 'desc');

            $tab = $request->query('tab');

            $body = [];

            // 判断是否要求返回指定的 TAB
            if ($tab == -1) {
                // 由于该页面只有一个特殊的 TAB ，因此不需要再做 TAB ID 的判断
                // 但是如果在其他类似页面存在大于 2 个 TAB 的情况，且需要返回特别 TAB 的可做独立判断
                // 如 if ($tab == ??) 这种，以上。
                $body[] = $this->getList(0, clone $query, $request);
                $body[] = $this->getList(1, clone $query, $request);
            } else {
                $body[] = $this->getList($tab, $query, $request);
            }

            return response()->json(['data' => $body, 'tab' => $tab]);
        }

        return view('admin/member/provider/index');
    }

    protected function getList($type, $query, Request $request)
    {
        $pageSize = $request->query('pageSize', 7);

        if ($user = $request->query('filter_field')) {
            $filter_field_val = $request->query('filter_field_val');
            if ($user == 1) {  // 用户名
                $query = $query->where('user', 'like', "%$filter_field_val%");
            } else {     //公司名称
                $query->whereHas('information', function ($query) use ($filter_field_val) {
                    $query->where('company', 'like', "$filter_field_val");
                });
            }
        }

        if ($state = $request->query('state')) {
            if ($state == 1) {  // 开启的
                $query->whereHas('store', function ($query) {
                    $query->where('audit_status', true);
                });
            } else {     //关闭的
                $query->whereHas('store', function ($query) {
                    $query->where('audit_status', false);
                });
            }
        }

        if ($county_id = $request->query('addr_county')) {
            $query->whereHas('information', function ($query) use ($county_id) {
                $query->where('county_id', $county_id);
            });
        }
        if ($city_id = $request->query('addr_city')) {

            $query->whereHas('information', function ($query) use ($city_id) {
                $query->where('city_id', $city_id);
            });
        }
        if ($province_id = $request->query('addr_province')) {
            $query->whereHas('information', function ($query) use ($province_id) {
                $query->where('province_id', $province_id);
            });
        }

        if ($start = $request->query('time_1')) {
            $query = $query->where('created_at', '>=', date('Y-m-d', strtotime($start)));
        }
        if ($end = $request->query('time_2')) {
            $query = $query->where('created_at', '<=', date('Y-m-d', strtotime($end)));
        }

        // 类型为 1 表示待审核
        if ($type == 1) {
            $query->whereHas('store', function ($query) {
                $query->where('audit_status', false);
            });
        }

        $query->whereHas('store', function ($query) {
            $query->where('audit_message', '');
        });

        $collection = $query->paginate($pageSize);
        $list       = $this->listProcessHandler($collection);

        return [
            'detail'         => $list,
            'pagingConfData' => [
                'page'     => $collection->currentPage(),
                'pageSize' => $pageSize,
                'total'    => $collection->total(),
            ],
        ];
    }

    protected function listProcessHandler($collection)
    {
        $data = [];

        foreach ($collection as $member) {
            $data[] = [
                'id'          => $member->id,
                'name'        => $member->user,
                'company'     => $member->information->company,
                'district'    => Area::getName($member->information->province_id) .
                    ' ' .
                    Area::getName($member->information->city_id),
                'time'        => date('Y-m-d', strtotime($member->created_at)), //店铺的申请时间
                'operate'     => $member->store->audit_status, // 1 开启  0 关闭
                'state'       => $member->store->audit_status == 1 ? '开启' : '关闭',
                'edit_url'    => route('admin.provider.edit', [$member->id]),
                'del_url'     => route('admin.provider.destroy', [$member->id]),
                'examine_url' => route('admin.provider.auth-details', [$member->id]),
            ];
        }

        return $data;
    }

    /**
     * 供应商审核页面
     *
     * @param $id
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function authDetails($id)
    {
        $member = Member::findOrFail($id);

        $business     = [

            'img'   => AttachmentPrivateFiles::where('id',
                $member->information->business_license)->first()->adminRoute(),
            'img_s' => AttachmentPrivateFiles::where('id',
                $member->information->business_license)->first()->adminRoute(),
            'text'  => '营业执照副本',
        ];
        $organization = [
            'img'   => AttachmentPrivateFiles::where('id',
                $member->store->organization_code_cert)->first()->adminRoute(),
            'img_s' => AttachmentPrivateFiles::where('id',
                $member->store->organization_code_cert)->first()->adminRoute(),
            'text'  => '组织机构代码证',
        ];

        $legal_b = [

            'img'   => AttachmentPrivateFiles::where('id',
                $member->information->legal_identity_b)->first()->adminRoute(),
            'img_s' => AttachmentPrivateFiles::where('id',
                $member->information->legal_identity_b)->first()->adminRoute(),
            'text'  => '身份证(正面)',
        ];

        $legal_a = [

            'img'   => AttachmentPrivateFiles::where('id',
                $member->information->legal_identity_a)->first()->adminRoute(),
            'img_s' => AttachmentPrivateFiles::where('id',
                $member->information->legal_identity_a)->first()->adminRoute(),
            'text'  => '身份证(背面)',
        ];

        $data = [$business, $organization, $legal_a, $legal_b];

        foreach (AttachmentPrivateFiles::where('id', $member->store->authorization)->get() as $auth) {
            $item            = [
                'img'   => route('private.admin.image', [$auth->id]),
                'img_s' => route('private.admin.image', [$auth->id]),
                'text'  => '授权书',
            ];
            $authorization[] = $item;
        }

        if (isset($authorization)) {
            $data = array_merge($data, $authorization);
        }

        return view('admin/member/provider/authstr', ['member' => $member, 'cert' => $data]);
    }

    /**
     * 同意审核
     *
     * @param $id
     *
     * @return \Illuminate\Http\Response
     */
    public function audit($id)
    {
        // 更新店铺的 字段
        $store = Store::findOrFail($id);

        $store->audit_status = 1;
        $store->audit_end    = date('Y-m-d H:i:s');
        $store->save();

        return redirect()->route('admin.provider.index');
    }

    public function refuse(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'message' => 'required|string',
        ]);

        if ($validator->fails()) {
            return response('Error', 403);
        }

        // 更新店铺的 字段
        $store = Store::findOrFail($id);

        $store->audit_end     = date('Y-m-d H:i:s');
        $store->audit_message = $request->input('message');
        $store->save();

        return redirect()->route('admin.provider.index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {

        $member = Member::where('id', $id)->first();

        return view('admin/member/provider/edit')->with('member', $member);  //此处用来页面渲染数据
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $member = Member::findOrFail($id);

        if ($password = $request->input('pw')) {
            $member->password = \Hash::make($password);
        }
        $member->save();
        $store_id = $member->store->id;

        $data = [
            'audit_status' => $request->input('status'),
            'level'        => $request->input('store_level'),
        ];
        if ($real_name_authentication = $request->input('real_name_authentication')) {
            $data['real_name_authentication'] = 1;
        }else{
            $data['real_name_authentication'] = 0;
        }
        if ($provider_authentication = $request->input('provider_authentication')) {
            $data['provider_authentication'] = 1;
        }else{
            $data['provider_authentication'] = 0;
        }

        Store::findOrFail($store_id)->update($data);
        return redirect()->route('admin.provider.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $store = Member::findOrFail($id);
        $store->delete();

        return $this->index($request);
    }

    /**
     * 批量删除  循环遍历id进行删除
     *
     * @param Request $request
     *
     * @return mixed
     * @throws ModelNotFoundException
     * @throws \Exception
     */
    public function batchRemove(Request $request)
    {
        try {
            return \DB::transaction(function () use ($request) {
                $arr = $request->input('ids');
                foreach ($arr as $member_id) {
                    $member = Member::findOrFail($member_id);
                    $member->delete();
                }

                return $this->index($request);
            });
        } catch (ModelNotFoundException $e) {
            throw $e;
        }
    }


    /**
     * 证件资料的信息 编辑页面
     *
     * @param $id
     *
     * @return string
     */
    static public function fileInfo($id)
    {
        $member = Member::where('id', $id)->first();

        $business     = [

            'img'   => AttachmentPrivateFiles::where('id',
                $member->information->business_license)->first()->adminRoute(),
            'img_s' => AttachmentPrivateFiles::where('id',
                $member->information->business_license)->first()->adminRoute(),
            'text'  => '营业执照副本',
        ];
        $organization = [
            'img'   => AttachmentPrivateFiles::where('id',
                $member->store->organization_code_cert)->first()->adminRoute(),
            'img_s' => AttachmentPrivateFiles::where('id',
                $member->store->organization_code_cert)->first()->adminRoute(),
            'text'  => '组织机构代码证',
        ];

        $data = [$business, $organization];
        foreach (AttachmentPrivateFiles::where('id', $member->store->authorization)->get() as $auth) {
            $item            = [
                'img'   => route('private.admin.image', [$auth->id]),
                'img_s' => route('private.admin.image', [$auth->id]),
                'text'  => '授权书',
            ];
            $authorization[] = $item;
        }

        if (isset($authorization)) {
            $data = array_merge($data, $authorization);
        }

        return json_encode($data);
    }

    /**
     * 假数据 TODO 后期需要修改
     * @return string
     */
    static public function condition()
    {
        $data = [
            '0' => [
                'code' => 1,
                'text' => '用户名',
            ],
            [
                'code' => 2,
                'text' => '公司名称',
            ],
        ];

        return json_encode($data);
    }


}
